/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.sql;

import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import java.lang.reflect.Field;
import java.sql.JDBCType;
import javax.persistence.Column;
import lombok.Getter;
import lombok.Setter;

/**
 * 字段<br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
public final class Identifier extends Named {

  /** 实体字段 */
  @Setter private Field field;

  /** 实体类型 */
  @Getter @Setter private Class<?> type;

  /** 字段类型，主要解决无实体字段的而出现的字段类型问题 */
  @Getter @Setter private JDBCType jdbcType;

  public Identifier(String name) {
    super(name);
  }

  public Identifier(Field field) {
    super(field.getName());
    this.field = field;
  }

  public Identifier(Class<?> type, Field field) {
    super(field.getName());
    this.type = type;
    this.field = field;
  }

  public Field getField() {
    if (field == null && type != null) {
      try {
        field = ReflectUtil.getField(type, this.getName());
      } catch (Exception e) {
        // 忽略
      }
    }

    return field;
  }

  public String getColumnName() {
    if (field != null) {
      Column column = field.getAnnotation(Column.class);
      if (column != null) {
        return column.name();
      }
    }

    return StrUtil.toUnderlineCase(super.getName());
  }

  @Override
  public String getName() {
    return field != null ? field.getName() : StrUtil.toCamelCase(super.getName());
  }
}
